package com.suyx.job.service.impl;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.suyx.job.dao.GoodsInfoRepository;
import com.suyx.job.entity.GoodsInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.service.IGoodsInfoService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/18 0018 11:50
 * @Description:
 */
@Slf4j
@Service
public class GoodsInfoServiceImpl extends MyServiceImpl<GoodsInfo,Integer> implements IGoodsInfoService {
	
	private GoodsInfoRepository goodsInfoRepository;

    @Autowired
    public GoodsInfoServiceImpl(GoodsInfoRepository repository) {
        super(repository);
        this.goodsInfoRepository = repository;
    }

	@Override
	public Page findGoodsPage(GoodsInfo goodsInfo, Integer page, Integer limit) {
		return new Page(
				goodsInfoRepository.findAll((Root<GoodsInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(goodsInfo.getGoodsName())){
                        predicates.add(cb.like(root.get("goodsName").as(String.class), "%"+goodsInfo.getGoodsName() + "%"));
                    }
                    if(!StringUtils.isEmpty(goodsInfo.getRemark())){
                        predicates.add(cb.like(root.get("remark").as(String.class), "%"+goodsInfo.getRemark() + "%"));
                    }
                    if(!StringUtils.isEmpty(goodsInfo.getRoleId())){
                        predicates.add(cb.equal(root.get("roleId").as(String.class), goodsInfo.getRoleId()));
                    }
                    if(!StringUtils.isEmpty(goodsInfo.getStatus())){
                        predicates.add(cb.equal(root.get("status").as(String.class), goodsInfo.getStatus()));
                    }
                    return  query.where(predicates.toArray(new Predicate[0]))
                    		.orderBy(cb.asc(root.get("goodsId").as(Integer.class))).getRestriction();
                }, PageRequest.of(page,limit)));
	}

	@Override
	public GoodsInfo findByRoleIdAndGoodsCode(Integer roleId, Integer goodsCode) {
		return goodsInfoRepository.findByRoleIdAndGoodsCode(roleId, goodsCode);
	}

	@Override
	public GoodsInfo findByRoleIdAndGoodsName(Integer roleId, String goodsName) {
		return goodsInfoRepository.findByRoleIdAndGoodsName(roleId, goodsName);
	}
}
